// miniprogram/pages/card/card.js
const app = getApp()
const db = wx.cloud.database();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cards: [],
    total: 0,
    page: 1,
    memberInfo: {}
  },

  getUserProfile() {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log('card页面的用户信息',res)
        this.setData({
          avatarUrl: res.userInfo.avatarUrl,
          userInfo: res.userInfo,
          hasUserInfo: true,
          loginStatus: res.userInfo.nickName
        })
        try {
          wx.setStorageSync('avatarUrl', res.userInfo.avatarUrl)
          wx.setStorageSync('userInfo', res.userInfo)
          wx.setStorageSync('hasUserInfo', true)
          wx.setStorageSync('nickName', res.userInfo.nickName)
        } catch (e) {
          console.log('写入用户信息发生错误')
        }

        wx.cloud.callFunction({
          name: 'login',
          data: {
            'avatarUrl': res.userInfo.avatarUrl,
            'nickName': res.userInfo.nickName
          },
          success: res => {
            console.log('[云函数] [login] 调用成功', res)
            this.setData({
              loginStatus: res.result.data.nickName,
              isCoach: res.result.data.isCoach
            });
            try {
              wx.setStorageSync('nickName', res.result.data.nickName)
              wx.setStorageSync('isCoach', res.result.data.isCoach)
              wx.setStorageSync('openid', res.result.data._openid)
              this.setData({
                memberInfo: res.result.data
              })
            } catch (e) {
              console.log('写入用户信息发生错误')
            }
          },
          fail: err => {
            console.error('[云函数] [login] 调用失败', err)
          }
        })
      }
    })
  },
  onClickLike: function (e) {
    let id = e.currentTarget.dataset.id
    console.log(id)
    let avatarUrl = wx.getStorageSync('avatarUrl');
    let nickName = wx.getStorageSync('nickName')

    wx.cloud.callFunction({
      name: 'addLike',
      data: {
        'cardId': id,
        'avatarUrl': avatarUrl,
        'nickName': nickName
      },
      success: res => {
        console.log(res)
        wx.showToast({
          title: res.result.message,
        })

        if (!res.result.success) {
          return
        }
        let cardList = this.data.cards
        for (var i = 0; i < cardList.length; i++) {
          let card = cardList[i]
          if (card._id == id) {
            if (!card.likeNo) {
              card.likeNo = 0
            }
            if (res.result.cancel) {
              card.likeNo = card.likeNo ==0 ? 0 : card.likeNo - 1
              card.isLike = false
            } else {
              card.likeNo = card.likeNo + 1
              card.isLike = true
            }
          }
        }

        this.setData({
          cards: cardList
        })

      },
      fail: err => {
      }
    })
  },

  onClickPreviewImg: function (e) {
    let card = e.currentTarget.dataset.card
    let index = e.currentTarget.dataset.index
    wx.previewImage({
      current: card.images[index],
      urls: card.images,
    })
  },
  checkIsLogin: function () {
    let _openid = wx.getStorageSync('openid')
    if (!_openid) {
      wx.showModal({
        title: '登陆',
        content: '你还未登陆，请先登陆！',
        confirmText: '确认',
        cancelText: '取消',
        success: res => {
          console.log(res)
          if (res.confirm) {
            this.getUserProfile()
          }
        }
      })
      return false
    }
    return true
  },
  onAddCardClick: function () {
    if (!this.checkIsLogin()) {
      return
    }
    wx.navigateTo({
      url: './add/add',
    })
  },

  onClickUser: function (e) {
    var card = e.currentTarget.dataset.card
    wx.navigateTo({
      url: '../userDetail/detail?openid=' + card._openid + '&nickName=' + card.userInfo.nickName + '&avatarUrl=' + card.userInfo.avatarUrl,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('card page')
    this.refreshAllCards();
    this.checkNewVersion();
  },
  // 检查版本更新
  checkNewVersion() {
    if (wx.canIUse('getUpdateManager')) { // 用户版本更新
      let updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate((res) => {
        // 请求完新版本信息的回调
        console.log('getUpdateManager', res)
        if (res.hasUpdate) {
          updateManager.onUpdateReady(() => {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: res => {
                if (res.confirm) {
                  // 新版本已经下载好，调用applyUpdate应用新版本，并且重启
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(() => { // 新版本下载失败 需要用户手动旧版本删除，下载新版本
            wx.showModal({
              title: '更新失败',
              content: '新版本下载失败，请删除当前小程序，重新搜索下载～'
            })
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log("onShow")
    this.getTabBar().init();
    this.getMemberInfo();
    this.refreshAllCards();
  },

  getMemberInfo: function () {
    let _openid = wx.getStorageSync('openid')
    if (!_openid) {
      return
    }

    let memberInfo = wx.getStorageSync('memberInfo')
    if (memberInfo.isMember) {
      this.setData({
        memberInfo: memberInfo
      })
    }
    wx.cloud.callFunction({
      name: 'getMemberInfo',
      data: {},
      success: res => {
        console.log('getMemberInfo', res)
        try {
          wx.setStorageSync('memberInfo', res.result.userInfo)
        } catch (e) {
          console.log('写入用户信息发生错误')
        }
        this.setData({
          memberInfo: res.result.userInfo
        })
      },
      fail: err => {
        console.error(err)
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  refreshAllCards: function () {
    this.setData({
      page: 1,
      pagesize: 20,
      onRefresh: false //重新加载数据
    });
    wx.showNavigationBarLoading(); //在标题栏中显示加载
    wx.cloud.callFunction({
      name: 'getCardList',
      data: {
        'page': this.data.page,
        'pageSize': 20
      },
      success: res => {
        console.log(res);
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
        if (res.result.cardList) {
          let cardList = res.result.cardList;
          const likeTasks = cardList.map((card, index) => this.getIsLikePromise(card));
          Promise.all(likeTasks)
            .then(data => {
              console.log(data);
              for (var i = 0; i < data.length; i++) {
                this.data.cards[i].isLike = data[i].total > 0;
              }
              this.setData({
                cards: this.data.cards
              });
            })
            .catch(e => {
              console.log(e);
            });
          this.setData({
            cards: res.result.cardList
          });
        }
      },
      fail: err => {
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
        console.log(err);
      }
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log('fresh')
    this.refreshAllCards();
  },
  getIsLikePromise(card) {
    let openid = wx.getStorageSync('openid')
    return db.collection('like-list').where({
      cardId: card._id,
      _openid: openid
    }).count()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('bottom');
    this.data.page++
    this.setData({
      page: this.data.page,
      onRefresh: false
    });
    const db = wx.cloud.database();
    wx.cloud.callFunction({
      name: 'getCardList',
      data: {
        'page': this.data.page,
        'pageSize': 20
      },
      success: res => {
        console.log(res)
        if (res.result.cardList) {
          if (res.result.cardList == 0) {
            this.data.page--
            this.setData({
              page: this.data.page
            });
          } else {
            let cardList = res.result.cardList
            this.setData({ cards: this.data.cards.concat(cardList) })
            const likeTasks = cardList.map((card, index) => this.getIsLikePromise(card));
            Promise.all(likeTasks)
              .then(data => {
                console.log(data);
                for (var i = 0; i < data.length; i++) {
                  for (var k = 0; k < this.data.cards.length; k++) {
                    if (cardList[i]._id == this.data.cards[k]._id) {
                      console.log('isTrue')
                      this.data.cards[k].isLike = data[i].total > 0;
                    }
                  }
                }
                this.setData({
                  cards: this.data.cards
                });
              })
              .catch(e => {
                console.log(e);
              });
          }
        }
      },
      fail: err => {
        console.log(err)
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

